#include "log_inner_common.h"

#include "msg_logger.h"
#ifdef USE_ANDROID_LOG
#include <android/log.h>
#endif

#if defined (__MACH__) && defined (__APPLE__)
#include <libgen.h>
#endif

SFLogFunction __logprintf = _safety_log_out;
bool sflog::sf_log_init(const char *, const char *)
{    
    return true;
}

#if defined (__MACH__) && defined (__APPLE__)
#define BASENAME(file) basename((char *) file)
#else
#define BASENAME(file) basename(file)
#endif

#define NEED_TIME_LOG
void _safety_log_out(const char *file, int /*file_len*/, const char */*func*/, int /*func_len*/, int line, int level, const char *format, ...)
{
#ifdef USE_ANDROID_LOG
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_INFO, "log", format, args);
    __android_log_print(ANDROID_LOG_INFO, "log", "\n");
    va_end(args);
#else
#ifdef NEED_TIME_LOG
#define TIME_PREFIX "%02d:%02d:%02d.%03ld"
#define TIME_VALUE result->tm_hour, result->tm_min, result->tm_sec, tv.tv_usec/1000,
#define TIME_DEFINE  struct timeval tv; \
                     gettimeofday(&tv, NULL); \
                     struct tm *result = localtime(&(tv.tv_sec));
#else
#define TIME_PREFIX
#define TIME_VALUE
#define TIME_DEFINE
#endif

    TIME_DEFINE
    va_list args;
    va_start(args, format);
    switch(level){
    case LOG_ERROR:
        fprintf(stderr, TCS_BOLD_RED TIME_PREFIX "ERROR [%s.%d] ", TIME_VALUE BASENAME(file), line );
        break;
    case LOG_WARN:
        fprintf(stderr, TCS_YELLOW TIME_PREFIX " WARN [%s.%d] ", TIME_VALUE BASENAME(file), line );
        break;
    case LOG_INFO:
        fprintf(stderr, TCS_GREEN TIME_PREFIX " INFO [%s.%d] ", TIME_VALUE BASENAME(file), line );
        break;
    case LOG_DEBUG:
        fprintf(stderr, TCS_BLUE TIME_PREFIX " DEBUG [%s.%d] ", TIME_VALUE BASENAME(file), line );
        break;
    case LOG_DUMP:
        fprintf(stderr, TCS_GRAY TIME_PREFIX " DUMP [%s.%d] ", TIME_VALUE BASENAME(file), line );
        break;
    default:
        fprintf(stderr, TCS_CYAN TIME_PREFIX " OTHER [%s.%d] ", TIME_VALUE BASENAME(file), line );
        break;
    }
    vfprintf(stderr, format, args);
    fprintf(stderr, TCS_NONE "\n");
    va_end(args);    
#endif
}
